import useUserStore from '@/stores/user';
import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import CommonInput from '@/pages/OrderModule/common/components/CommonInput';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { useFetch } from '@/pages/OrderModule/common/hooks/useFetch';
import { Button, Col, Form, Row, message } from 'antd';
import { useState } from 'react';

function CodeFormItem(props) {
  const [countdown, setCountdown] = useState(0);
  const userInfo = useUserStore((state) => state.userInfo);
  const {
    fetch: sendCaptchaApi,
    loading,
    data: mergeInfo,
  } = useFetch(() => {
    return new Promise((resolve) => {
      setTimeout(() => {
        return resolve(true);
      }, 2000);
    });
  });

  function sendCaptcha() {
    sendCaptchaApi().then((res) => {
      message.success('验证码已发送，请查收');
      // 开始倒计时
      setCountdown(60);
      let interval = setInterval(() => {
        setCountdown((prevCount) => {
          if (prevCount <= 1) {
            clearInterval(interval);
            return 0;
          }
          return prevCount - 1;
        });
      }, 1000);
    });
  }
  return (
    <Row gutter={16}>
      <Col flex="auto">
        <CommonInput {...props} placeholder="请输入手机验证码" />
      </Col>
      <Col>
        <Button disabled={countdown > 0} onClick={() => sendCaptcha()} type="primary" size="middle" ghost>
          {countdown > 0 ? `${countdown}秒` : '获取验证码'}
        </Button>
      </Col>
    </Row>
  );
}

function AccountVerifyModal(props) {
  const [form] = Form.useForm();
  const userInfo = useUserStore((state) => state.userInfo);

  return (
    <CommonForm
      formProps={{
        form,
        initialValues: {
          mobile: userInfo.mobile || '',
          code: '',
        },
        onValuesChange(changedValues, values) {
          props.onChange && props.onChange(values);
        },
      }}
      columns={[
        {
          block: <Typography>为确保数据安全，该操作需二次验证</Typography>,
        },
        {
          name: 'mobile',
          Component: CommonInput,
          props: {
            prefix: '手机号',
            disabled: true,
          },
          style: { marginTop: 16 },
        },
        {
          name: 'code',
          rules: [{ required: true, message: '请输入手机验证码' }],
          style: { marginTop: 16 },
          render() {
            return <CodeFormItem />;
          },
        },
      ]}
    ></CommonForm>
  );
}

export default AccountVerifyModal;
